package org.example.les01;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Demo01_UDPEchoClient {
    //声明一个DatagramSocket对象
    private DatagramSocket socket;
    //声明服务器IP
    private String serverIP;
    //声明服务器端口号
    private int serverPort;
    //通过构造方法指定服务器IP和端口号
    public Demo01_UDPEchoClient(String serverIP,int serverPort) throws SocketException {
        //初始化DatagramSocket对象
        this.socket=new DatagramSocket();
        //指定服务器IP和端口号
        this.serverIP=serverIP;
        this.serverPort=serverPort;
    }

    /**
     * 客户端服务
     * @throws IOException
     */
    public void start() throws IOException {
        System.out.println("客户端已启动.");
        //循环处理客户端的输入
        while(true){
            System.out.println("->");
            //定义in
            Scanner in=new Scanner(System.in);
            //1.获取用户的输入
            String request=in.nextLine();
            //判断输入是否规范
            if(request==null||request.isEmpty()){
                System.out.println("输入不能为空.");
                continue;
            }
            //2.创建目标的SocketAddress对象
            SocketAddress address=new InetSocketAddress(serverIP,serverPort);
            //3.定义一个用于包装请求数据的DatagramPacket
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8), 0, request.getBytes().length, address);
            //4.发送真实的数据到服务器
            socket.send(requestPacket);
            //5.用DatagramPacket接收服务器响应的数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            //6.接收数据
            socket.receive(responsePacket);
            //7.解析数据得到响应
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            //8.打印响应结果
            System.out.printf("request=%s,response=%s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        Demo01_UDPEchoClient client=new Demo01_UDPEchoClient("127.0.0.1",8888);
        client.start();
    }
}
